package cn.itcast.crm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	
	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	public List<Customer> findNoAssociationCustomers() {
		//FixedAreaId is null
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		//FixedAreaId is ?
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		//解锁关联动作
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		System.out.println(customerIdStr);
		
		// 切割字符串1,2,3
		String[] customerIdArray = customerIdStr.split(",");
		
		for (String str : customerIdArray) {
			int id = Integer.parseInt(str);
			customerRepository.updateFixedAreaId(fixedAreaId,id);
		}
	}

	@Override
	public void regist(Customer customer) {
		System.out.println(customer);
		customerRepository.save(customer);
	}
	
	@Override
	public Customer findByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}	

	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,
				password);
	}

	//订单输入流程中的根据地址查询到定区的WebService请求
	@Override
	public String findFixedAreaIdByAddress(String address) {
		Customer customer = customerRepository.findByAddress(address);
		if(customer != null){
			return customer.getFixedAreaId();
		}else{
			return null;
		}
	}
}
